package com.ws.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyuncs.exceptions.ClientException;
import com.ws.oss.service.OssService;
import com.ws.oss.utils.ConstantPropertiesUtil;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author ws
 * @create 2024-12-03 16:56
 */
@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadFlie(MultipartFile file) {

        //获取阿里云存储相关常量

        String endPoint = ConstantPropertiesUtil.END_POINT;

        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;

        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;

        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String uploadUrl = null;


        try {

            //判断oss实例是否存在：如果不存在则创建，如果存在则获取

            OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);

            if (!ossClient.doesBucketExist(bucketName)) {

                //创建bucket

                ossClient.createBucket(bucketName);

                //设置oss实例的访问权限：公共读

                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);

            }


            //获取上传文件流

            InputStream inputStream = file.getInputStream();

            //构建日期路径：avatar/2019/02/26/文件名

            String filePath = new DateTime().toString("yyyy/MM/dd");


            //文件名：uuid.扩展名

            String original = file.getOriginalFilename();

            String fileName = UUID.randomUUID().toString();

            String fileType = original.substring(original.lastIndexOf("."));

            String newName = fileName + fileType;

            String fileUrl = filePath + "/" + newName;


            //文件上传至阿里云

            ossClient.putObject(bucketName, fileUrl, inputStream);


            // 关闭OSSClient。

            ossClient.shutdown();


            //获取url地址

            uploadUrl = "http://" + bucketName + "." + endPoint + "/" + fileUrl;


        } catch (IOException e) {

            e.printStackTrace();

        }


        return uploadUrl;
    }

    @Override
    public void delete(String url) {
        System.out.println(url);
        System.out.println("*****************************************");
        String endPoint = ConstantPropertiesUtil.END_POINT;

        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;

        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;

        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;


        //https://edu-20241203.oss-cn-beijing.aliyuncs.com/2024/12/05/46a79436-d697-47c0-85dd-57d9c8422a1f.jpg
        String replaceStr="http://"+bucketName+"."+endPoint+"/";
        String fileName=StringUtils.substringAfterLast(url,replaceStr);
        System.out.println(fileName);
        System.out.println("*****************************************");
        try {
            //判断oss实例是否存在：如果不存在则创建，如果存在则获取
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);;
            ossClient.deleteObject(bucketName, fileName);

            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
            ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                System.out.println(objectSummary.getKey());
            }
            // 关闭OSSClient。

            ossClient.shutdown();



        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    public static void main(String[] args) {
        String endPoint = "oss-cn-beijing.aliyuncs.com";
        String bucketName = "edu-20241203";
        String a="https://edu-20241203.oss-cn-beijing.aliyuncs.com/2024/12/05/46a79436-d697-47c0-85dd-57d9c8422a1f.jpg";
        String b="https://edu-20241203.oss-cn-beijing.aliyuncs.com/";
        String replaceStr="https://"+bucketName+"."+endPoint+"/";
        String substring = StringUtils.remove(a,replaceStr);
        System.out.println(substring);
    }
}
